<template>
  <div class="container">

    <div class="userinfo">
      <img :src="userinfo.avatarUrl" alt="">
      <p>{{userinfo.nickName}}</p>
    </div>

    <button open-type="getUserInfo" @getuserinfo="bindGetUserInfo" @click="getUserInfo1">获取用户信息</button>

    <!-- <YearProgress></YearProgress> -->

    <button @click='scanBook' class='btn'>添加图书</button>
  </div>
</template>

<script>
import { showSuccess, post, showModal, get } from "@/util";
import Vue from "vue";
import AppVue from "../../App.vue";

export default {
  data() {
    return {
      userinfo: {
        nickName: ""
      },
    };
  },
  methods: {
    async addBook(isbn) {
      const res = await post("/addbook", {
        isbn,
        openid: this.userinfo.openid,
        // user_info: JSON.stringify(this.userinfo)
      });
      showModal("添加成功", `${res.title}添加成功`);
    },
    getSetting() {
      let self = this;

      return new Promise(resolve => {
        wx.getSetting({
          success: function (res) {
            if (res.authSetting["scope.userInfo"]) {
              wx.getUserInfo({
                success: function (res) {
                  self.userinfo = res.userInfo;
                  global.data.userInfo = self.userinfo;
                  resolve(true);
                }
              });
            } else {
              console.log("用户还未授权过");
            }
          }
        });
      });
    },
    getopenId() {
      let self = this;

      return new Promise(resolve => {
        wx.login({
          success: res => {
            // 发送 res.code  至 https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

            var code = res.code;

            if (code) {
              //登录code 获取 用户id，
              wx.request({
                data: {},
                url: `https://api.weixin.qq.com/sns/jscode2session?appid=wx4adebe0a8ba8911e&secret=d27ea46db05cb1f35b71c4fdcd15f94f&js_code=${code}&grant_type=authorization_code`,
                success: function (res) {
                  self.userinfo.openid = res.data.openid;
                  global.data.userInfo = self.userinfo;
                  self.addUser();
                  resolve(true);
                }
              });
            } else {
              console.log("获取用户登录态失败：" + res.errMsg);
            }
          }
        });
      });
    },
    getUserInfo1() {
      if (wx.canIUse("button.open-type.getUserInfo")) {
        // 用户版本可用
      } else {
        console.log("请升级微信版本");
      }
    },
    bindGetUserInfo(e) {
      if (e.mp.detail.rawData) {
        showSuccess("登录成功");
        this.userinfo = e.target.userInfo;
        this.getopenId();
      } else {
        console.log("用户按了拒绝按钮");
      }
    },
    login() {
      let user = wx.getStorageSync("userinfo");
      const self = this;
      if (!user) {
        qcloud.setLoginUrl(config.loginUrl);
        qcloud.login({
          success: function (userinfo) {
            qcloud.request({
              url: config.userUrl,
              login: true,
              success(userRes) {
                showSuccess("登录成功");
                wx.setStorageSync("userinfo", userRes.data.data);
                self.userinfo = userRes.data.data;
                global.data.userInfo = self.userinfo;
              }
            });
          }
        });
      }
    },
    scanBook() {
      wx.scanCode({
        success: res => {
          if (res.result) {
            this.addBook(res.result);
          }
        }
      });
    },
    async addUser() {
      const {
        avatarUrl,
        city,
        country,
        gender,
        language,
        nickName,
        openid,
        province
      } = this.userinfo;

      const res = await post("/addUser", {
        avatarUrl,
        city,
        country,
        gender,
        language,
        nickName,
        openid,
        province      });

    }
  },
  async created() {
    await this.getSetting();
    await this.getopenId();
  }
};
</script>

<!--suppress CssInvalidPropertyValue -->
<style rel="stylesheet/sass" lang="scss">
.container {
  padding: 0 30rpx;
}
.userinfo {
  margin-top: 100rpx;
  text-align: center;
  img {
    width: 150rpx;
    height: 150rpx;
    margin: 20rpx;
    border-radius: 50%;
  }
}
.btn {
  margin-top: 12px;
}
</style>
